package map.android.baidu.carpool.page.usercenter;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.widget.MToast;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.OrderDetailData;
import map.android.baidu.carpool.data.impl.OrderFinishData;
import map.android.baidu.carpool.data.impl.OrderListData;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.home.OrderDetailPage;
import map.android.baidu.carpool.page.pay.CreateCarerCommentPage;
import map.android.baidu.carpool.page.pay.OrderPayPage;
import map.android.baidu.carpool.response.OrderDetailResponse;
import map.android.baidu.carpool.response.OrderFinishResponse;
import map.android.baidu.carpool.response.OrderListResponse;
import map.android.baidu.carpool.response.OrderListResponse.OrderListRoot.OrderItem;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.CarPoolReceiptDialog;
import map.android.baidu.carpool.utils.CarpoolAlertDialog;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.utils.ToastForCarpool;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshListView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zhangtongyu on 15/3/28.
 * 订单列表页面
 */
public class OrderListPage extends CarpoolBasePage{

    private static String TAG = "orderlistpg";

    private Context mContext;
    private Resources mRes;
    private LayoutInflater mInflater;

    private View mView;
    private PullToRefreshListView mPtrlv;
    private ListView mList;
    private OrderItemAdapter mAdapter;

    private TextView mNoOrderListTv;

    private ArrayList<OrderItem> mAllOrderListData;

    private static int mPn = 0;
    private static int mDeltaPn;

    /**
     * 是否需要刷新
     */
    private static boolean needClearList = false;
    
    private OrderListResponse mPullUpResponse;
    private IDataStatusChangedListener<OrderListResponse> pullUpListener = new IDataStatusChangedListener<OrderListResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<OrderListResponse> data, OrderListResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    mPullUpResponse = response;
                    if(response.data.total <= 0){
                        mNoOrderListTv.setVisibility(View.VISIBLE);
                        mPtrlv.setVisibility(View.GONE);
                    } else {
                        mNoOrderListTv.setVisibility(View.GONE);
                        mPtrlv.setVisibility(View.VISIBLE);
                        pullUpUpdateData(response);
                    }
                } else {
                    mPn = mPn - mDeltaPn;
                    MToast.show(mContext , "网络连接异常，请检查网络");
                }
            } else {
                mPn = mPn - mDeltaPn;
                MToast.show(mContext , "网络连接异常，请检查网络");
            }
            pullUpUpdatePageAndUi();
            showLoadingDialog(false);
        }
    };

    private OrderListResponse mPullDownResponse;
    private IDataStatusChangedListener<OrderListResponse> pullDownListener = new IDataStatusChangedListener<OrderListResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData comNetData, OrderListResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    mPullDownResponse = response;
                    if(response.data.total <= 0){
                        mNoOrderListTv.setVisibility(View.VISIBLE);
                        mPtrlv.setVisibility(View.GONE);
                    } else {
                        mNoOrderListTv.setVisibility(View.GONE);
                        mPtrlv.setVisibility(View.VISIBLE);
                        pullDownUpdateData(response);
                    }
                } else {
                    MToast.show(mContext , "网络连接异常，请检查网络");
                }
            } else {
                MToast.show(mContext , "网络连接异常，请检查网络");
            }
            pullDownUpdatePageAndUi();
            showLoadingDialog(false);
        }
    };

    private void pullDownUpdatePageAndUi() {
        if (mPullDownResponse == null) {
            return;
        }
        int totalPages = 0;
        double pagesDou = (double)mPullDownResponse.data.total / 10;
        totalPages = (int)Math.ceil(pagesDou);
        LogUtils.d("zty", "当前页面+==" + mPn + "**" + totalPages);
        mPtrlv.onRefreshComplete();
        if (0 == mPn) {
            if (totalPages <= 1) {
                mPtrlv.setMode(Mode.PULL_DOWN_TO_REFRESH);
            } else {
                mPtrlv.setMode(Mode.BOTH);
            }
        } else if (mPn == (totalPages - 1)) {
            mPtrlv.setMode(Mode.PULL_DOWN_TO_REFRESH);
        } else {
            mPtrlv.setMode(Mode.BOTH);
        }
    }

    private void pullUpUpdatePageAndUi() {
        if (mPullUpResponse == null) {
            return;
        }
        int totalPages = 0;
        double pagesDou = (double)mPullUpResponse.data.total / 10;
        totalPages = (int)Math.ceil(pagesDou);
        LogUtils.d("zty", "当前页面+==" + mPn + "**" + totalPages);
        mPtrlv.onRefreshComplete();
        if (0 == mPn) {
            if (totalPages <= 1) {
                mPtrlv.setMode(Mode.PULL_DOWN_TO_REFRESH);
            } else {
                mPtrlv.setMode(Mode.BOTH);
            }
        } else if (mPn == (totalPages - 1)) {
            mPtrlv.setMode(Mode.PULL_DOWN_TO_REFRESH);
        } else {
            mPtrlv.setMode(Mode.BOTH);
        }
    }

    private void pullUpUpdateData(OrderListResponse response) {
        ArrayList<OrderItem> tempList = response.data.orderList;
        mAllOrderListData.addAll(tempList);
        mAdapter.setListData(mAllOrderListData, true);
    }

    private void pullDownUpdateData(OrderListResponse response) {
        ArrayList<OrderItem> tempList = response.data.orderList;
        mAllOrderListData.clear();
        mAllOrderListData.addAll(tempList);
        mAdapter.setListData(tempList , true);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mContext = APIProxy.res().getBaseActivity();
        mRes = APIProxy.res().getResources();
        mInflater = APIProxy.res().getInflater();
        if(mView == null) {
            mPn = 0;
            mAllOrderListData = new ArrayList<OrderItem>();
            mView = mInflater.inflate(R.layout.layout_order_list_page, null);
            initTitleBar(mView);
            initPtrListView(mView);
            showLoadingDialog(true);
            requestPullDownOrderListData();
        }else{
            ViewGroup parent = (ViewGroup) mView.getParent();
            if(parent!=null)
                parent.removeView(mView);
        }

        if(isNavigateBack()){
            handleBackArgFromOrderDetail();
        }
        return mView;
    }

    private void handleBackArgFromOrderDetail() {
        Bundle backArg = getBackwardArguments();
        if(backArg != null && backArg.containsKey(OrderDetailResponse.class.getName())){
            OrderDetailResponse backOrderDetailResponse = (OrderDetailResponse) backArg.getSerializable(OrderDetailResponse.class.getName());
            if(backOrderDetailResponse != null && backOrderDetailResponse.data != null && mAllOrderListData != null && mAllOrderListData.size() != 0){
                for (int index = 0; index < mAllOrderListData.size(); index++){
                    if(mAllOrderListData.get(index) != null) {
                        if (backOrderDetailResponse.data.orderId.equals(mAllOrderListData.get(index).orderId)){
                            mAllOrderListData.get(index).orderStatusDesc = backOrderDetailResponse.data.orderStatusDesc;
                            mAllOrderListData.get(index).orderStatusId = backOrderDetailResponse.data.orderStatusId;
                            if(mAdapter != null){
                                mAdapter.setListData(mAllOrderListData, true);
                            }
                        }
                    }
                }
            }
        }
    }

    private void handleCheckOrderStatusRescponse(OrderDetailResponse detailResponse) {
            if(detailResponse != null && detailResponse.data != null && mAllOrderListData != null && mAllOrderListData.size() != 0){
                for (int index = 0; index < mAllOrderListData.size(); index++){
                    if(mAllOrderListData.get(index) != null) {
                        if (detailResponse.data.orderId.equals(mAllOrderListData.get(index).orderId)){
                            mAllOrderListData.get(index).orderStatusDesc = detailResponse.data.orderStatusDesc;
                            mAllOrderListData.get(index).orderStatusId = detailResponse.data.orderStatusId;
                            if(mAdapter != null){
                                mAdapter.setListData(mAllOrderListData, true);
                            }
                        }
                    }
                }
            }
        }

    private void initTitleBar(View mView) {
        ImageView backBt = (ImageView) mView.findViewById(R.id.left_view);
        TextView titleTv = (TextView) mView.findViewById(R.id.center_view);

        backBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getTask().goBack();
            }
        });
        backBt.setVisibility(View.VISIBLE);

        titleTv.setText("我的订单");
        titleTv.setVisibility(View.VISIBLE);
    }

    private void initPtrListView(View mView) {

        mNoOrderListTv = (TextView) mView.findViewById(R.id.tv_no_order_list);

        mPtrlv = (PullToRefreshListView) mView.findViewById(R.id.carpool_order_list_ptrlv);
        mPtrlv.setMode(Mode.DISABLED);
        mPtrlv.setBackgroundColor(0xededed);
        mPtrlv.setDisableScrollingWhileRefreshing(false);
        mPtrlv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPn = 0;
                requestPullDownOrderListData();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mDeltaPn = 1;
                turnPage(mDeltaPn);
            }
        });

        FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT);
        mList = mPtrlv.getRefreshableView();
        mList.setLayoutParams(params1);
        mList.setBackgroundColor(0xededed);
        mList.setVerticalScrollBarEnabled(false);
        mList.setDividerHeight(0);
        mList.setHeaderDividersEnabled(false);
        mList.setFooterDividersEnabled(false);
        mList.setCacheColorHint(0x00000000);
        mList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mList.setFadingEdgeLength(0);
        mAdapter = new OrderItemAdapter(mContext);
        mList.setAdapter(mAdapter);
    }

    public void turnPage(int deltaNum) {
        mPn = mPn + deltaNum;
        requestPullUpOrderListData();
    }

    private void requestPullUpOrderListData() {
        OrderListData orderListData = new OrderListData(mContext);
        orderListData.setPn(mPn);
        orderListData.post(pullUpListener);
    }

    private void requestPullDownOrderListData(){
        showLoadingDialog(true);
        OrderListData orderListData = new OrderListData(mContext);
        orderListData.setPn(mPn);
        orderListData.post(pullDownListener);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public boolean onBackPressed() {
        return super.onBackPressed();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public class OrderItemAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater mInflater;
        private Resources mRes;
        private List<OrderItem> listData;
        private OrderItemViewHolder mViewHolder;

        public OrderItemAdapter(Context context) {
            mContext = context;
            mInflater = APIProxy.res().getInflater();
            mRes = APIProxy.res().getResources();
            listData = new ArrayList<OrderItem>();
        }

        /**
         * @param list      数据
         * @param needClear 是否需要清除之前的数据
         */
        public void setListData(List<OrderItem> list, boolean needClear) {
            if (needClear) {
                listData.clear();
            }
            listData.addAll(list);
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            if (listData != null) {
                return listData.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            if (listData != null) {
                return listData.get(position);
            } else {
                return null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final OrderItem item = listData.get(position);
            if (convertView == null || convertView.getTag() == null) {
                mViewHolder = new OrderItemViewHolder();
                convertView = mInflater.inflate(R.layout.layout_item_order_list, null);
                if (position == 0) {
                    convertView.setPadding(0, 10, 0, 0);
                }
                mViewHolder.carerNameTv = (TextView) convertView.findViewById(R.id.tv_carer_name_order_item);
                mViewHolder.orderStatusTv = (TextView) convertView.findViewById(R.id.tv_status_order_item);
                mViewHolder.orderTimeTv = (TextView) convertView.findViewById(R.id.tv_time_order_item);
                mViewHolder.startPlaceTv = (TextView) convertView.findViewById(R.id.tv_start_address_order_item);
                mViewHolder.endPlaceTv = (TextView) convertView.findViewById(R.id.tv_end_address_order_item);
                mViewHolder.orderArrow = (LinearLayout) convertView.findViewById(R.id.lin_order_item_arrow);

                convertView.setTag(mViewHolder);
            } else {
                Object tag = convertView.getTag();
                if (tag instanceof OrderItemViewHolder) {
                    mViewHolder = (OrderItemViewHolder) tag;
                }
            }
            updateTitle(item, mViewHolder);
            updateContent(item, mViewHolder);
            updateStatus(item, mViewHolder);

            if (item.orderStatusId == 2 || item.orderStatusId == 0) {

                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CarPoolReceiptDialog waitDialog = new CarPoolReceiptDialog(mActivity, item.orderId, 0);
                        waitDialog.show();
                    }
                });
            } else {
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundleForDetail = new Bundle();
                        bundleForDetail.putString("orderId", item.orderId);
                        bundleForDetail.putString("from", OrderListPage.class.getName());
                        APIProxy.navi().navigateTo(OrderDetailPage.class, bundleForDetail);
                    }
                });
            }

            return convertView;
        }

        private void updateStatus(final OrderItem item, OrderItemViewHolder mViewHolder) {
            if (!TextUtils.isEmpty(item.orderStatusDesc)) {
                mViewHolder.orderStatusTv.setVisibility(View.VISIBLE);
                mViewHolder.orderStatusTv.setText(item.orderStatusDesc);
            } else {
                mViewHolder.orderStatusTv.setVisibility(View.GONE);
            }
            if (item.orderStatusId == 7 || item.orderStatusId == 10 || item.orderStatusId == 11) {
                mViewHolder.orderStatusTv.setTextColor(mRes.getColor(R.color.carpool_blue));
                mViewHolder.orderStatusTv.setEnabled(true);
                if (item.orderStatusId == 7) {
                    mViewHolder.orderStatusTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            gotoPay(item);
                        }
                    });
                } else if (item.orderStatusId == 10 || item.orderStatusId == 11) {
                    mViewHolder.orderStatusTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            alertComfirmGetOnDialog(item);
                        }
                    });
                }
            } else {
                mViewHolder.orderStatusTv.setTextColor(mRes.getColor(R.color.car_text_gray));
                mViewHolder.orderStatusTv.setEnabled(false);
            }
        }

        private void updateContent(OrderItem item, OrderItemViewHolder mViewHolder) {
            if (!TextUtils.isEmpty(item.startPlace)) {
                mViewHolder.startPlaceTv.setText(item.startPlace);
            } else {
                mViewHolder.startPlaceTv.setText("未知位置");
            }

            if (!TextUtils.isEmpty(item.arrivePlace)) {
                mViewHolder.endPlaceTv.setText(item.arrivePlace);
            } else {
                mViewHolder.endPlaceTv.setText("未知位置");
            }

        }

        private void updateTitle(OrderItem item, OrderItemViewHolder mViewHolder) {
            SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm");
            if (!TextUtils.isEmpty(item.startTime)) {
                String timeString = format.format(new Date(Long.parseLong(item.startTime) * 1000));
                mViewHolder.orderTimeTv.setText(timeString);
            } else {
                mViewHolder.orderTimeTv.setText("未知时间");
            }

            if (!TextUtils.isEmpty(item.carerNickname)) {
                mViewHolder.carerNameTv.setVisibility(View.VISIBLE);
                mViewHolder.carerNameTv.setText(item.carerNickname);
            } else {
                mViewHolder.carerNameTv.setVisibility(View.GONE);
            }
        }

        /**
         * 确认上车
         */
        public void getOnCar(final OrderItem item) {
            OrderFinishData orderFinishData = new OrderFinishData(mActivity);
            orderFinishData.setBduss(UserInfoSetting.getBduss());
            orderFinishData.setOrderId(item.orderId);
            showLoadingDialog(true);
            orderFinishData.post(new IDataStatusChangedListener<OrderFinishResponse>() {
                @Override
                public void onDataStatusChanged(ComNetData<OrderFinishResponse> comNetData,
                                                OrderFinishResponse orderFinishResponse,
                                                int i) {
                    if (orderFinishResponse != null) {
                        if (orderFinishResponse.getErrorNo() == 0) {
                            ToastForCarpool.show(mActivity, "已确认上车");
                            final OrderDetailData orderDetailData = new OrderDetailData(mContext);
                            orderDetailData.setOrderId(item.orderId);
                            orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
                                @Override
                                public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData, OrderDetailResponse orderDetailResponse, int i) {
                                    showLoadingDialog(false);
                                    if (orderDetailResponse != null && orderDetailResponse.data != null) {
                                        if (orderDetailResponse.data.orderStatusId == 12) {
                                            Bundle bundleForComment = new Bundle();
                                            bundleForComment.putSerializable(OrderDetailResponse.class.getName(), orderDetailResponse);
                                            APIProxy.navi().navigateTo(CreateCarerCommentPage.class, bundleForComment);
                                        } else {
                                            ToastForCarpool.show(mContext, "订单状态已发生改变,请重新操作");
                                            handleCheckOrderStatusRescponse(orderDetailResponse);
                                        }
                                    } else {
                                        Bundle bundleForDetail = new Bundle();
                                        bundleForDetail.putString("orderId", item.orderId);
                                        APIProxy.navi().navigateTo(OrderDetailPage.class, bundleForDetail);
                                    }
                                }
                            });
                        } else {
                            showLoadingDialog(false);
                            ToastForCarpool.show(mContext, "确认上车失败，请进入详情页确认或稍后再试");
                        }
                    }
                }
            });
        }

        /**
         * 去支付
         */
        private void gotoPay(OrderItem item) {
            showLoadingDialog(true);
            if (!checkNetworkStatus(true)) {
                return;
            }
            OrderDetailData orderDetailData = new OrderDetailData(mActivity);
            orderDetailData.setOrderId(item.orderId);
            orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
                @Override
                public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData,
                                                OrderDetailResponse orderDetailResponse,
                                                int i) {
                    showLoadingDialog(false);
                    if (orderDetailResponse != null && orderDetailResponse.data != null) {
                        if (orderDetailResponse.data.orderStatusId == 7) {
                            Bundle bundleForPay = new Bundle();
                            bundleForPay.putString("from", OrderListPage.class.getName());
                            bundleForPay.putString("orderId", orderDetailResponse.data.orderId);
                            APIProxy.navi().navigateTo(OrderPayPage.class, bundleForPay);
                        } else if (orderDetailResponse.data.orderStatusId == 8) {
                            /**
                             * 抢单成功，支付超时
                             */
                            ToastForCarpool.show(mContext, "支付已超时,请进入详情查看");
                            handleCheckOrderStatusRescponse(orderDetailResponse);
                        }else {
                            ToastForCarpool.show(mContext, "订单状态已发生改变,请重新操作");
                            handleCheckOrderStatusRescponse(orderDetailResponse);
                        }
                    } else {
                        ToastForCarpool.show(mActivity, "请求数据失败");
                    }
                }
            });
        }

        private void alertComfirmGetOnDialog(final OrderItem item) {
            CarpoolAlertDialog.Builder builder = new CarpoolAlertDialog.Builder(getActivity());
            builder.setTitle("小主确认搭乘后，车费将转账给车主，请于顺风车服务结束后确认");
            builder.setNegativeButton("取消", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //直接结束dialog
                }
            });
            builder.setPositiveButton("确定", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getOnCar(item);
                }
            });
            builder.create().show();
        }
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public class OrderItemViewHolder {
        public TextView orderTimeTv;
        public TextView carerNameTv;
        public TextView startPlaceTv;
        public TextView endPlaceTv;
        public TextView orderStatusTv;
        public LinearLayout orderArrow;
    }

}
